import Vue from 'vue'

//侧边栏左右拖动宽度指令
const drag = Vue.directive('drag', {
    bind: function (el) {
        let treeLeft = $(el).find('.tree-left');
        let treeRight = $(el).find('.tree-right');
        //创建一个line元素
        let line = $('<div class="line"></div>');
        line.css({width: '4px', height: '100%', position: 'absolute', right: 0, top: 0,backgroundColor: '#fff', cursor: 'w-resize', zIndex: 999});
        treeLeft.append(line);
        $(line).bind('mousedown', function(e) {
            let ev = e || event,
                oLeft = $(this).offset().left,
                disX = ev.clientX;
            $(document).bind('mousemove', function(e) {
                let ev = e || event,
                    x = oLeft + (ev.clientX - disX);
                if(x <= 150) x = 150;
                if(x >= $(el).outerWidth(true) - 210) x = $(el).outerWidth(true) - 210;
                $(line).css({left: x + 'px'});
                $(treeLeft).css({width: x + 'px'});
                $(treeRight).css({width: $(el).outerWidth(true) - $(treeLeft).outerWidth(true) - 15 + 'px'});
            });
            $(document).bind('mouseup', function() {
                $(document).unbind('mousemove');
                $(document).unbind('mouseup');
            });
        });
        //窗口发生改变时触发
        $(window).resize(function(e) {
            let w = $(el).outerWidth(true);         //得到此时屏幕的宽度
            let x = $(line).offset().left;          //拖线偏移左边的距离
            $(treeRight).css({width: w - x - 15 + 'px'});
        });
    }
});

export {drag}